/*
** communication.c for  in /home/gomes_m//rattrapage/server
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Tue Jul 23 12:43:54 2013 mickael gomes
** Last update Sat Jul 27 15:14:22 2013 mickael gomes
*/

#include		<unistd.h>
#include		<stdio.h>
#include		"struct.h"
#include		"prototypes.h"

t_func			tab[] =
  {
    {&get_fork, "ls"},
    {&get_fork, "mv"},
    {&get_fork, "cp"},
    {&get_fork, "pwd"},
    {&get_fork, "mkdir"},
    {&get_fork, "touch"},
    {&get_fork, "rm"},
    {&get_fork, "rmdir"},
    {&my_cd, "cd"},
  };

int			check_cmd(char *buff)
{
  int			i = 0;

  while (i < 9)
    {
      if (my_strcmp(buff, tab[i].flag))
	i++;
      else
	return (i);
    }
  return (-1);
}

void			send_response(int pipefd[2], t_list *list)
{
  int			len;

  xclose(pipefd[1]);
  if ((len = read(pipefd[0], list->cmd->result, 1024)) > 0)
    {
      list->cmd->result[len] = 0;
      len = xwrite(list->fd, list->cmd->result, my_strlen(list->cmd->result));
      if (len != my_strlen(list->cmd->result))
	xwrite(list->fd, &list->cmd->result[len], my_strlen(list->cmd->result) - len);
    }
  else
    {
      len = xwrite(list->fd, CMD_EXEC, my_strlen(CMD_EXEC));
      if (len != my_strlen(CMD_EXEC))
	xwrite(list->fd, &CMD_EXEC[len], my_strlen(CMD_EXEC) - len);
    }
}

void			get_cmd(t_list *list)
{
  char			*buff;

  buff = xmalloc(512);
  if (xrecv(list->fd, buff, 512 + 1, MSG_DONTWAIT) == 1)
    {
      list->disconnected = 1;
      return ;
    }
  buff = treat_buff(buff);
  if (!my_strcmp(buff, "closing"))
    {
      list->disconnected = 1;
      return ;
    }
  list->cmd->cmd = get_first_part(buff);
  list->cmd->cmd_tab = my_str_to_wordtab(buff);
  list->cmd->arguments = get_remains(buff);
  go_to_current_dir(list->current_dir);
  if ((list->cmd->pos = check_cmd(list->cmd->cmd)) != -1)
    tab[list->cmd->pos].f(list);
  else
    my_putstr(list->fd, "Command not found\n", 0);
}
